package com.platform.zuul.route;

import com.apache.api.vo.ResultEntity;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * @description:
 * @author: Hou Dayu
 * @date: Created in 2020/3/17
 */
@Configuration
public class CustomZuulConfig {

    @Autowired
    ZuulProperties zuulProperties;
    @Autowired
    ServerProperties server;

    @Bean
    public CustomRouteLocator routeLocator() {
        CustomRouteLocator routeLocator = new CustomRouteLocator(this.server.getServletPrefix(), this.zuulProperties);
        buildBlackWhite(routeLocator);
        return routeLocator;
    }

    private void buildBlackWhite(CustomRouteLocator routeLocator) {//黑白名单缓存加载
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                }
                Map<String,Object> params = new HashMap();
                params.put("modelTypes","s_sysZuulBlack");
                params.put("resultObjType","list");
                params.put("datasource", "plateform");
                params.put("resultType", "objInfo");
                params.put("sqlKeyId", "sqlKeyId");
                params.put("sysPass", ConfigUtil.getInstance().interfacePass());
                ResultEntity res = LoadRpcService.service().doService("iusService","dymicSql","xml",params,null);
                if(null != res.getEntity()) {
                    List<Map<String,String>> list = (List)res.getEntity();
                    int count = list.size();
                    for(int i=0;i<count;i++) {
                        Map<String,String> info = list.get(i);
                        String ip = info.get("useIp");
                        routeLocator.setRoutsCache("black.white", ip, info);
                    }
                }
            }
        }).start();
    }
}

